<template>
  <div class="app-container">
    <el-form class="formList" :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-row>
        <!-- <el-col :span="8"> -->
        <el-form-item label="卡券编号" prop="cardNo">
          <el-input v-model="queryParams.cardNo" placeholder="请输入卡券编号" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <!-- </el-col>
        <el-col :span="8"> -->
        <el-form-item label="卡券密码" prop="cardSecret">
          <el-input v-model="queryParams.cardSecret" placeholder="请输入卡券密码" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <!-- </el-col>
        <el-col :span="8"> -->
        <el-form-item label="数据状态" prop="cardStatus">
          <el-select v-model="queryParams.cardStatus" placeholder="请选择数据状态" clearable size="small">
            <el-option v-for="dict in cardStatusOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <!-- </el-col> -->
      </el-row>

      <el-row>

        <!-- <el-col :span="8"> -->
        <el-form-item style="margin-left:10px ;">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <!-- <el-button icon="el-icon-search" size="mini" @click="colsePro()">返回</el-button> -->
        </el-form-item>
        <!-- </el-col>
        <el-col :span="8"> -->

        <!-- </el-col> -->
      </el-row>
    </el-form>
    <el-row class="row-mbinfo" style="  margin-left: 0px; margin-right: 0px;">
      <el-row>
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
            v-hasPermi="['activity:batch:add']">新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <!--            <el-button-->
          <!--              type="success"-->
          <!--              plain-->
          <!--              icon="el-icon-edit"-->
          <!--              size="mini"-->
          <!--              :disabled="single"-->
          <!--              @click="handleUpdate"-->
          <!--              v-hasPermi="['activity:batch:edit']"-->
          <!--            >修改-->
          <!--            </el-button>-->
        </el-col>
        <el-col :span="1.5" style="margin-left: 10px">
          <!--          <el-button-->
          <!--            type="danger"-->
          <!--            plain-->
          <!--            icon="el-icon-delete"-->
          <!--            size="mini"-->
          <!--            :disabled="multiple"-->
          <!--            @click="handleDelete"-->
          <!--            v-hasPermi="['activity:batch:remove']"-->
          <!--          >删除-->
          <!--          </el-button>-->
        </el-col>
        <el-col style="margin-left: 10px" :span="1.5">
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </el-row>
    <div class="divTable">
      <el-table border v-loading="loading" :data="cardList" @selection-change="handleSelectionChange">
        <el-table-column label="卡券编号" min-width="150" align="center" prop="cardNo" :show-overflow-tooltip="true" />
        <el-table-column label="卡券类型" align="center" prop="cardTypeStr" :show-overflow-tooltip="true" />
        <el-table-column label="卡券内容信息" align="center" prop="name" :show-overflow-tooltip="true" />
        <el-table-column label="sku" align="center" prop="skuName" :show-overflow-tooltip="true" />

        <el-table-column label="卡券密码" align="center" prop="cardSecretStr">
          <template slot-scope="scope">
            <span style="color: #00AAFF;" @click="showPhone(scope.row)">
              {{ scope.row.cardSecretStr }}
            </span>
          </template>
        </el-table-column>

        <el-table-column label="数据状态" align="center" prop="cardStatus" :formatter="cardStatusFormat">

          <template slot-scope="scope">
            <el-switch v-if="scope.row.cardStatus != 2" v-model="scope.row.cardStatus" active-value="1" inactive-value="0"
              @change="handleStatusChange(scope.row)"></el-switch>

            <span v-if="scope.row.cardStatus == 2">
              已领取
            </span>
          </template>

        </el-table-column>
        <el-table-column label="发送状态" align="center" prop="sendStatus">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.sendStatus" active-value="1" inactive-value="0"
              @change="handleSendStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="有效开始时间" align="center" prop="startDate" :show-overflow-tooltip="true" />
        <el-table-column label="有效结束时间" align="center" prop="endDate" :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <!--            <el-button-->
            <!--              size="mini"-->
            <!--              type="text"-->
            <!--              icon="el-icon-edit"-->
            <!--              @click="handleUpdate(scope.row)"-->
            <!--              v-hasPermi="['activity:batch:edit']"-->
            <!--            >修改-->
            <!--            </el-button>-->
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-if="scope.row.cardStatus == '0'" v-hasPermi="['activity:batch:remove']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />

    </div>
    <el-dialog :title="title" :visible.sync="addOpen" width="500px" append-to-body @keyup.enter.native="submitForm">
      <el-form ref="batchForm" :model="giftBatch" :rules="rules" label-width="100px">
        <el-form-item label="发卡数量:" prop="cardNumber">
          <el-input v-model="giftBatch.cardNumber" maxlength="4" placeholder="请输入发卡数量" />
        </el-form-item>

        <el-form-item label="兑换类型:" prop="cardTypeStr">
          {{ giftBatch.cardTypeStr }}
          <!-- <el-input disabled
            v-model="giftBatch.cardTypeStr"></el-input> -->
        </el-form-item>

        <div style="margin-left: 80%">
          <el-button type="primary" size="mini" @click="addCard" :loading="addButton">确 定</el-button>
        </div>

      </el-form>
    </el-dialog>

    <!-- 添加或修改卡券明细对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="550px" append-to-body @keyup.enter.native="submitForm">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="卡券编号" prop="cardNo">
          {{ form.cardNo }}
        </el-form-item>
        <el-form-item label="金额">
          {{ form.cardAmountStr }} 元
        </el-form-item>

        <el-form-item label="卡券密码" prop="cardSecret">
          <el-input v-model="form.cardSecret" placeholder="请输入卡券密码" />
        </el-form-item>

        <el-form-item label="领取时间" prop="startDate">
          <div>
            <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="getTime" type="datetimerange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions0">
            </el-date-picker>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listCard, getCard, delCard, addCard, updateCard, updateDataStatus, updateSendStatus} from "@/api/activity/card";
import { updateBatch, getBatch } from "@/api/activity/giftBatch";

//验证卡券
let checkCardNumber = (rule, value, callback) => {
  if (value > 2000) {
    callback(new Error())
  } else {
    callback()
  }
}

export default {
  name: "Card",
  components: {},
  data () {
    return {
      //添加卡券确认按钮
      addButton: false,
      //批次对象
      giftBatch: {},
      //批次ID
      batchId: null,
      //新增弹出层
      addOpen: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 卡券明细表格数据
      cardList: [],
      // 弹出层标题
      title: "",
      //查看详细标题
      viewTitle: "",
      // 是否显示弹出层
      open: false,
      //是否显示查看详细弹出层
      viewOpen: false,
      //查看详细数据
      showData: [],
      // 数据状态字典
      cardStatusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cardNo: null,
        cardSecret: null,
        cardStatus: null,
      },
      getTime: [],

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        cardNumber: [
          { required: true, message: '请输入发卡数量', trigger: 'blur' },
          { min: 1, max: 4, message: '发卡数量在 1 到 2000 张之间', trigger: 'blur' },
          { type: 'number', validator: checkCardNumber, message: '发卡数量在 1 到 2000 张之间' }
        ],
        cardAmountStr: [
          { required: true, message: '请输入发卡金额', trigger: 'blur' },
          { min: 1, max: 4, message: '发卡金额 1 到 2000 元之间', trigger: 'blur' },
          { type: 'number', validator: checkCardNumber, message: '发卡金额 1 到 2000 元之间' }
        ],
        startDate: [
          { required: true, message: '请选择卡券日期', trigger: 'blur' },
        ]
      },
      pickerOptions0: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },

    };
  },
  created () {
    this.getBatch()
    this.getList();
    this.getDicts("activity_coupon_state").then(response => {
      this.cardStatusOptions = response.data;
    });
  },
  methods: {
    //新增当前批次下卡券
    addCard () {
      // this.giftBatch.startDate = this.getTime[0];
      // this.giftBatch.endDate = this.getTime[1];
      this.giftBatch.batchId = this.queryParams.batchId
      this.$refs["batchForm"].validate(valid => {
        if (valid) {
          this.addButton = true
          updateBatch(this.giftBatch).then(response => {
            this.addOpen = false
            this.addButton = false
            this.getList();
          })
        }
      })


    },
    //查询当前批次
    getBatch () {
      getBatch(this.$route.params.batchId).then(response => {
        this.giftBatch = response.data
      })
    },
    /** 查询卡券明细列表 */
    getList () {
      this.batchId = this.$route.params.batchId;
      this.loading = true;
      this.queryParams.batchId = this.batchId
      listCard(this.queryParams).then(response => {
        this.cardList = response.rows;
        this.total = response.total;

        this.loading = false;
      });
    },
    // 数据状态字典翻译
    cardStatusFormat (row, column) {
      return this.selectDictLabel(this.cardStatusOptions, row.cardStatus);
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    //显示隐藏手机号
    showPhone (row) {
      row.PhoneUpdate = row.cardSecret;
      if (row.cardSecretStr.indexOf("*") != -1 == false) {
        row.PhoneUpdate = row.cardSecretStr;
        var len = row.cardSecret.length - 2 - 2;
        var xing = '';
        for (var i = 0; i < len; i++) {
          xing += "*";
        }
        row.cardSecretStr = row.cardSecret.substring(0, 2) + xing + row.cardSecret.substring(row.cardSecret.length - 2)
      } else {
        row.cardSecretStr = row.PhoneUpdate;
      }
    },
    // 表单重置
    reset () {
      this.form = {
        cardUid: null,
        batchId: null,
        customerUid: null,
        customerName: null,
        cardName: null,
        cardPhone: null,
        cardNo: null,
        cardSecret: null,
        cardAmount: null,
        cardStatus: null,
        cardType: null,
        createTime: null,
        createUid: null,
        updateTime: null,
        updateUid: null,
        startDate: null,
        endDate: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.cardUid)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.giftBatch.cardNumber = null
      this.reset();
      this.getTime = null
      this.addOpen = true;
      this.title = "添加当前批次下卡券";
    },
    /** 查看详情按钮操作 **/
    handleShowDetail (row) {
      this.viewOpen = true;
      this.viewTitle = "查看卡券明细";
      this.showData = [];
      this.columns.forEach(item => {
        this.showData.push({
          label: item.label,
          value: row[item.dataIndex]
        })
      })
    },
    handCloseDetail () {
      this.viewOpen = false
      this.showData = []
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const cardUid = row.cardUid || this.ids
      getCard(cardUid).then(response => {
        this.form = response.data;
        var mycars = new Array()

        mycars[0] = this.form.startDate
        mycars[1] = this.form.endDate
        this.getTime = mycars
        this.open = true;
        this.title = "修改卡券明细";
      });
    },
    //取消
    colsePro () {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push({
        path: "/activity/Card/batch",
      });
    },
    /** 提交按钮 */
    submitForm () {
      // this.form.startDate = this.getTime[0];
      // this.form.endDate = this.getTime[1];
      debugger
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.cardUid != null) {
            updateCard(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCard(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const cardUids = row.cardUid || this.ids;
      this.$confirm('是否确认删除卡券明细编号为"' + cardUids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delCard(cardUids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('/prod-api/activity/card/export', {
        ...this.queryParams
      }, `卡券明细数据.xlsx`)
    },
    //修改数据状态
    handleStatusChange (row) {
      let text = row.cardStatus === '0' ? '无效' : '有效'
      this.$confirm(
        '确定要把卡券编号："' + row.cardNo + '",设为' + text + '吗？',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function () {
          return updateDataStatus(row.cardUid, row.cardStatus)
        })
        .then(() => {
          this.msgSuccess('操作成功')
          this.getList()
        })
        .catch(function () {
          row.cardStatus = row.cardStatus === '0' ? '1' : '0'
        })
    },
    //修改数据发送状态
    handleSendStatusChange (row) {
      let text = row.sendStatus === '0' ? '未发送' : '已发送'
      this.$confirm(
        '确定要把卡券编号："' + row.cardNo + '",设为' + text + '吗？',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function () {
          return updateSendStatus(row.cardUid, row.sendStatus)
        })
        .then(() => {
          this.msgSuccess('操作成功')
          this.getList()
        })
        .catch(function () {
          row.sendStatus = row.sendStatus === '0' ? '1' : '0'
        })
    }
  }
};
</script>

<style scoped>
.product-div {
  background-color: #fff;
  position: relative;
  padding-right: 16px;
  padding-top: 54px;
  border: 2px solid #ebebeb;
  -moz-border-radius: 4px;
  border-radius: 4px;
  width: 1200px;
  margin: auto;
  top: 20px;
  bottom: -20px;
  margin-bottom: 50px;
}
</style>
